package com.example.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.example.entity.Roles;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.util.AliyunMessageUtil;
import com.example.util.ResponeMessageUtil;
import com.example.util.TokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;

@RestController
public class LoginController {
	
	@Autowired
	private UserService userService;
	
	HashMap<String,String>map=new HashMap<>();//保存手机号对应的号码
	@RequestMapping("/login")
	public Object login(String un,String pwd,String code,String phoneNumber) {
		
		User user = null;
		if(code !=null&&code !="") {//手机号登录
			//验证输入的短信码是否正确
			if(!map.get(phoneNumber).equals(code)) {
				return ResponeMessageUtil.ok("你输入的验证码有误",user);
			}
			//通过手机号查询用户
			user = userService.selectByProtectMTel(phoneNumber);
		}else {
			//调用service
			user = userService.selectByNameAndPwd(un, pwd);
		}
	
		if (user == null) {
			if (code !=null) {
				// 返回结果
				Map<String, Object> rMap = new HashMap<String, Object>();
				rMap.put("code", "0");
				rMap.put("msg", "您的手机号码不正确");
				return rMap;
			} else {
				// 返回结果
				Map<String, Object> rMap = new HashMap<String, Object>();
				rMap.put("code", "0");
				rMap.put("msg", "用户名密码错误或者");
				return rMap;
			}
			
		} else {
			if (user.getIsLockout().equals("2")) {
				// 返回结果
				Map<String, Object> rMap = new HashMap<String, Object>();
				rMap.put("code", "0");
				rMap.put("msg", "用户被锁定，请联系管理员解锁");
				return rMap;
			} else {
				// 用户名和密码正确，并且未锁定
				// 生成token
				String token = "";

				try {
					token = TokenUtil.sign(user, 60 * 60 * 1000);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JsonProcessingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}

		
		
		
		
		
		
				
				//把token和用户信息返回给页面
				//查询用户信息
				List<Roles> roles = userService.getRolesByUid(user.getId());
				user.setRoles(roles);
				String rids = "";
				for (int i = 0;i < roles.size(); i++) {
					if (i== roles.size()-1) {
						rids += roles.get(i).getId();
					}else {
						rids += roles.get(i).getId()+",";
					}
				}
				user.setRoleIds(rids);
				//返回结果
				Map<String, Object> map = new HashMap<>();
				map.put("code", "0");
				map.put("msg", "success");
				map.put("count", 0);
				map.put("data", user);
				map.put("token", token);
				return map;
			} 
		}
	}
	/**
     * 实现手机发送
     * @param map
     * @return
     */
    @PostMapping("/sendMobileCode")
    public Map<String,Object> sendMobileCode(String phoneNumber) throws ClientException{
        String randomNum = getSixNum();
        String jsonContent = "{\"code\":\"" + randomNum + "\"}";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("phoneNumber",phoneNumber);
        paramMap.put("jsonContent", jsonContent);
        SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap);
        if(!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) {
            if(sendSmsResponse.getCode() == null) {
                //这里可以抛出自定义异常
            	Map<String, Object> map = new HashMap<>();
            	map.put("msg", "error");
				return map;
            }
            if(!sendSmsResponse.getCode().equals("OK")) {
                //这里可以抛出自定义异常
            	Map<String, Object> map = new HashMap<>();
            	map.put("msg", "error");
				return map;
            }
        }
        //把验证码保存到map
        map.put(phoneNumber, randomNum);
        //手机号验证码发送成功
        Map<String, Object> map = new HashMap<>();
    	map.put("msg", randomNum);
		return map;
    }
   
    public static String getSixNum() {
		String str = "0123456789";
		StringBuilder sb = new StringBuilder(4);
		for (int i = 0; i < 6; i++) {
			char ch = str.charAt(new Random().nextInt(str.length()));
			sb.append(ch);
		}
		return sb.toString();
	}

}
